package com.fred

import androidx.compose.foundation.layout.*
import androidx.compose.desktop.ui.tooling.preview.Preview
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogState
import com.fred.bean.KeyStoreBean
import com.fred.util.ColorUtil
import com.fred.util.PropertiesUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File
import javax.swing.JFileChooser
import javax.swing.filechooser.FileNameExtensionFilter
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.key.*
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.PasswordVisualTransformation
import com.fred.bean.KeyStoreJson
import com.fred.dragdrop.PlatformDropTargetModifierDialog
import com.fred.dragdrop.dropTarget
import com.fred.util.FileUri
import com.fred.util.KeyStoreUtil
import com.fred.xlog.Log
import kotlinx.coroutines.withContext

private val jksFilter by lazy {
    FileNameExtensionFilter("*.jks", "jks")
}

private const val LAST_KEY_STORE_PATH = "lastKeyStorePathConfig"

@OptIn(ExperimentalComposeUiApi::class)
@Composable
@Preview
fun addKeyStore(isShow: MutableState<Boolean>,onAdded: (ksj:KeyStoreJson)->Unit) {
    if (isShow.value) {
        Dialog(
            onCloseRequest = {
                isShow.value = false
            },
            resizable = false,
            icon = painterResource("ic_add.svg"),
            title = "添加签名",
            state = DialogState(
                position = getPosition(600f, 370.8f),
                size = DpSize(600.dp, 370.8.dp)
            )
        ) {
            val keyStorePath: MutableState<String> = remember { mutableStateOf("") }
            val keyStorePassword: MutableState<String> = remember { mutableStateOf("") }
            val keyStore: KeyStoreBean = remember { KeyStoreBean() }
//            val keystoreAlias = remember { mutableStateOf(KeyStoreAlias())  }
            val alias = remember { mutableStateOf("") }
            val aliasPassword: MutableState<String> = remember { mutableStateOf("") }
            val density = LocalDensity.current.density
            val dropParent = remember(density) {
                PlatformDropTargetModifierDialog(
                    density = density,
                    window = this.window,
                )
            }
            val showError = remember { mutableStateOf(false) }
            val errorTitle = remember { mutableStateOf("") }
            val errorTip = remember { mutableStateOf("") }
            Box(modifier = Modifier.fillMaxWidth().fillMaxHeight(),
            contentAlignment = Alignment.Center){
                Column(modifier = Modifier.then(dropParent).padding(32.dp, 0.dp).sizeIn(minWidth = 400.dp, maxWidth = 400.dp)
                    .dropTarget(
                        onDragStarted = { _, _ ->
                            true
                        },
                        onDropped = { uris, _ ->
                            uris.forEach {
                                if (it is FileUri) {
                                    Log.i("path:${it.path}  :${it.mimeType} ${it.extension}")
                                    if (it.file.exists()) {
                                        keyStorePath.value = it.path
                                    }
                                }
                            }
                            if (keyStorePassword.value.isNotEmpty()) {
                                //先输入密码 再拖入文件
                                getKeyStore(keyStorePath.value,keyStorePassword.value,keyStore,alias)
                            }
                            false
                        }),
                    horizontalAlignment = Alignment.CenterHorizontally) {
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        verticalAlignment = Alignment.Bottom
                    ) {
                        var hasFocus by remember { mutableStateOf(false) }
                        TextField(
                            value = keyStorePath.value,
                            modifier = Modifier.defaultMinSize(2.dp, 1.dp).width(328.dp)
                                .onFocusChanged {
                                    hasFocus = it.hasFocus
                                    Log.i("onFocusChanged:${it.hasFocus}")
                                },
                            singleLine = true,
//                readOnly = true,
                            onValueChange = { str ->
                                keyStorePath.value = str
                                if (keyStorePassword.value.isNotEmpty()) {
                                    //先输入密码 再拖入文件
                                    getKeyStore(keyStorePath.value,keyStorePassword.value,keyStore,alias)
                                }
                            },
                            label = { Text("keystore路径") },
                            colors = TextFieldDefaults.textFieldColors(
                                textColor = ColorUtil.mainFont,
                                unfocusedIndicatorColor = ColorUtil.subFont,
                                focusedIndicatorColor = ColorUtil.subFont,
                                unfocusedLabelColor = ColorUtil.subFont,
                                focusedLabelColor = ColorUtil.subFont,
                                backgroundColor = Color.Transparent,
                                cursorColor = ColorUtil.subFont
                            ),
                            textStyle = TextStyle(fontSize = 12.sp)
                        )
                        var isEnable by remember { mutableStateOf(true) }
                        folderButton(isEnable, hasFocus) {
                            isEnable = false
                            coroutineScope.launch(Dispatchers.IO) {
                                val path = PropertiesUtil.getProperties(LAST_KEY_STORE_PATH,"lastKeyStorePath") ?: ""
                                val cd = File(path)
                                if (cd.exists()) {
                                    if (cd.isDirectory) {
                                        fileChooser.currentDirectory = cd
                                    } else {
                                        fileChooser.currentDirectory = cd.parentFile
                                    }
                                }
                                fileChooser.fileFilter = jksFilter
                                fileChooser.addChoosableFileFilter(jksFilter)
                                if (fileChooser.showOpenDialog(parentWindow) == JFileChooser.APPROVE_OPTION) {
                                    val f: File = fileChooser.selectedFile
                                    if (f.exists()) {
                                        keyStorePath.value = f.absolutePath
                                    }
                                }
                                isEnable = true
                            }
                        }
                    }

                    TextField(
                        value = keyStorePassword.value,
                        modifier = Modifier
                            .defaultMinSize(2.dp, 1.dp)
                            .fillMaxWidth(),
                        singleLine = true,
                        onValueChange = { str ->
                            keyStorePassword.value = str
                            Log.i("password:${keyStorePassword.value}")
                            if (keyStorePath.value.isNotEmpty()) {
                                getKeyStore(keyStorePath.value,keyStorePassword.value,keyStore,alias)
                            }
                        },
                        label = { Text("keystore密码") },
                        colors = TextFieldDefaults.textFieldColors(
                            textColor = ColorUtil.mainFont,
                            unfocusedIndicatorColor = ColorUtil.subFont,
                            focusedIndicatorColor = ColorUtil.subFont,
                            unfocusedLabelColor = ColorUtil.subFont,
                            focusedLabelColor = ColorUtil.subFont,
                            backgroundColor = Color.Transparent,
                            cursorColor = ColorUtil.subFont
                        ),
                        textStyle = TextStyle(fontSize = 12.sp),
                        visualTransformation = PasswordVisualTransformation()
                    )

                    Dropdown(
                        keyStore.alias, onMenuItemClick = {
                            alias.value = it.alias
                            aliasPassword.value = it.password
                        },
                        onclick = {

                        },
                        tip = alias.value.ifEmpty { "别名" },
                        tipColor = ColorUtil.mainFont,
                        minWidth = 400.dp,
                        maxWidth = 400.dp,
                        menuMaxHeight = 100.dp
                    ) {
                        Text(
                            it.alias, style = if (it.alias == alias.value) {
                                TextStyle.Default.copy(
                                    color = ColorUtil.selectFont,
                                    fontWeight = FontWeight.Bold
                                )
                            } else {
                                TextStyle.Default.copy(
                                    color = ColorUtil.mainFont,
                                    fontWeight = FontWeight.Normal
                                )
                            }
                        )
                    }


                    TextField(
                        value = aliasPassword.value,
                        modifier = Modifier.defaultMinSize(2.dp, 1.dp).fillMaxWidth().onPreviewKeyEvent{
                            if (it.type == KeyEventType.KeyUp && (it.key == Key.Enter ||it.key == Key.NumPadEnter)){
                                onAdd(keyStore,alias, aliasPassword, showError, errorTitle, errorTip, isShow, onAdded)
                                true
                            } else {
                                false
                            }
                        },
                        singleLine = true,
                        onValueChange = { str ->
                            aliasPassword.value = str
                        },
                        label = { Text("别名密码") },
                        colors = TextFieldDefaults.textFieldColors(
                            textColor = ColorUtil.mainFont,
                            unfocusedIndicatorColor = ColorUtil.subFont,
                            focusedIndicatorColor = ColorUtil.subFont,
                            unfocusedLabelColor = ColorUtil.subFont,
                            focusedLabelColor = ColorUtil.subFont,
                            backgroundColor = Color.Transparent,
                            cursorColor = ColorUtil.subFont
                        ),
                        textStyle = TextStyle(fontSize = 12.sp),
                        visualTransformation = PasswordVisualTransformation()
                    )
                    Spacer(modifier = Modifier.height(24.dp))
                    Button(onClick = {
                        onAdd(keyStore,alias, aliasPassword, showError, errorTitle, errorTip, isShow, onAdded)
                    },colors = ButtonDefaults.buttonColors(backgroundColor = ColorUtil.primary)) {
                        Text("  添  加  ")
                    }
                    errorDialog(errorTitle,errorTip,showError)
                }
            }
        }
    }
}

private fun onAdd(keyStore: KeyStoreBean,
                  alias:MutableState<String>,
                  aliasPassword: MutableState<String>,
                  showError:MutableState<Boolean>,
                  errorTitle:MutableState<String>,
                  errorTip:MutableState<String>,
                  isShow: MutableState<Boolean>,
                  onAdded: (ksj:KeyStoreJson)->Unit){
    val result = KeyStoreUtil.verificationAlias(keyStore,
        alias.value,aliasPassword.value)
    if (result.isSuccess()) {
        val keystoreJson = KeyStoreJson(result.keyStorePath,result.keyStorePassword,
            alias.value,aliasPassword.value)
        coroutineScope.launch(Dispatchers.IO) {
            val addResult = com.fred.bean.addKeyStore(keystoreJson)
            if (addResult) {
//                withContext(Dispatchers.Main) {
                    isShow.value = false
                    PropertiesUtil.setProperties(LAST_KEY_STORE_PATH,"lastKeyStorePath",keystoreJson.keyStorePath)
                    onAdded.invoke(keystoreJson)
//                }
            }else {
                errorTitle.value = "Fail"
                errorTip.value = "添加失败，请重试"
                showError.value = true
            }
        }
    } else {
        errorTitle.value = "Fail"
        errorTip.value = result.errorMess
        showError.value = true
    }
}

private fun getKeyStore(path:String,password:String,keyStore: KeyStoreBean,alias:MutableState<String>) {
    val bean = KeyStoreUtil.getKeyStore(path, password)
    if (bean.isSuccess()) {
        keyStore.keyStorePath = bean.keyStorePath
        keyStore.keyStorePassword = bean.keyStorePassword
        keyStore.alias.clear()
        keyStore.alias.addAll(bean.alias)
        if (keyStore.alias.size > 0) {
            val temp = keyStore.alias[0]
            alias.value = temp.alias
        }
    } else {
        keyStore.keyStorePath = ""
        keyStore.keyStorePassword = ""
        keyStore.alias.clear()
        alias.value = ""
    }
}